How can I use timer to stop another thread? [on hold]
Posted
by
Haoda Fu
on Programmers
See other posts from Programmers
or by Haoda Fu
Published on 2014-08-18T14:22:38Z
Indexed on
2014/08/18
16:43 UTC
Read the original article
Hit count: 288
c#
|multithreading
How can we stop another thread based on a timer?
I was trying to use timer to stop another thread. But I didn't got a success. To better illustrate my point and for your easy to understand the key issue. I made the following sample example.
Your help is really appreciated
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Timers;
namespace TestCodes
{
public static class Program
{
private static Thread nT = new Thread(PrintABC);
private static System.Timers.Timer aTimer;
public static void Main()
{
aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += TimerCallback;
aTimer.Interval = 1000;
aTimer.Enabled = true;
nT.Start();
Console.ReadLine();
}
private static void TimerCallback(Object o, ElapsedEventArgs e)
{
nT.Join();
Console.WriteLine("Complete the PrintABC");
GC.Collect();
}
private static void PrintABC()
{
for (int iter = 1; iter < 300; iter++)
{
Console.WriteLine(iter+"abc");
Console.ReadKey();
//Thread.Sleep(100);
}
}
}
}
© Programmers or respective owner